package com.weir.goods.entity;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

import jakarta.persistence.*;

import io.quarkus.hibernate.orm.panache.PanacheEntityBase;

/**
 * 商品分类
 * @author Administrator
 *
 */
@Entity
@Table(name = "goods_category", schema = "weir-goods")
@org.hibernate.annotations.Table(appliesTo = "goods_category",comment = "商品分类") 
public class GoodsCategory extends PanacheEntityBase implements Serializable {
	private static final long serialVersionUID = -3092777004955650288L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public Long id;
	@Column(columnDefinition = "varchar(50) COMMENT '名称'",length = 50)
	public String name;
	@Column(name = "parent_id",columnDefinition = "bigint COMMENT '父节点'")
	public Long parentId;
	@Column(columnDefinition = "int COMMENT '分类级别0,1,2...'")
	public Integer level;
	@Column(columnDefinition = "bit(1) COMMENT '是否显示'")
	public Boolean enable;
	@Column(columnDefinition = "int COMMENT '排序'")
	public Integer sort;
	@Column(columnDefinition = "varchar(100) COMMENT '图标'",length = 100)
	public String icon;
    // 标记不是数据库表字段
	@Transient
	public List<GoodsCategory> children;
	
	public String getName() {
		return name;
	}
	public Long getParentId() {
		return parentId;
	}
	public Integer getLevel() {
		return level;
	}
	public Integer getSort() {
		return sort;
	}
	/**
	 * 树形结构
	 * @return 
	 */
	public static List<GoodsCategory> tree() {
		List<GoodsCategory> listAll = listAll();
		return listAll.stream().filter(c -> (c.parentId == null || c.parentId == 0)).map((c) -> {
			c.children = getChildren(c, listAll);
			return c;
		}).sorted((c1, c2) -> {
			return c1.sort - c2.sort;
		}).collect(Collectors.toList());
	}
	/**
	 * 递归查找
	 * @param root
	 * @param listAll
	 * @return
	 */
	private static List<GoodsCategory> getChildren(GoodsCategory root, List<GoodsCategory> listAll) {
		return listAll.stream().filter(c -> {
			return c.parentId == root.id;
		}).map(c -> {
			c.children = getChildren(c, listAll);
			return c;
		}).sorted((c1, c2) -> {
			return c1.sort - c2.sort;
		}).collect(Collectors.toList());
	}
}
